<?php

namespace app\backend\service;
use app\common\model\MemberModel;
use app\common\RootService;
use app\common\model\MoneyRecordModel;

class MoneyRecordService extends RootService
{
    /**
     * 流水标签
     * @return array
     */
    public function coinLabel()
    {
        return ['methodLabel' => MoneyRecordModel::$methodLabel, 'stateLabel' => MoneyRecordModel::$stateLabel,
            'currencyLabel' => MoneyRecordModel::$currencyLabel, 'bindType' => MemberModel::$bindType,
            'color' => MoneyRecordModel::$color];
    }

    /**
     * 金币明细
     * @param array $params
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function lists(array $params)
    {
        $coinLabel = $this->coinLabel();
        // 数据源
        $coinList = $this->page($this->recordModel($params)->order(['rid' => 'desc']));
        // 数据处理
        array_walk($coinList['data'], function (&$row) use ($coinLabel) {
            $row['color'] = $coinLabel['color'][$row['currency']] ?? '--';
            $row['bindType'] = $coinLabel['bindType'][$row['bind_type']];
            $row['stateLabel'] = $coinLabel['stateLabel'][$row['state']] ?? '--';
            $row['methodLabel'] = $coinLabel['methodLabel'][$row['method']] ?? '--';
            $row['currencyLabel'] = $coinLabel['currencyLabel'][$row['currency']] ?? '--';
        });
        return $coinList;
    }

    /**
     * 流水记录模型
     * @param array $params
     * @return MoneyRecordModel
     */
    protected function recordModel(array $params)
    {
        $today = date('Y-m-d');
        // 筛选条件
        $where = [['mr.type', '=', 0], ['mr.method', 'not in', [2]], ['mr.state', '=', 3]];
        // 用户筛选
        empty($params['memberId']) || $where[] = ['m.id', '=', $params['memberId']];
        // 用户ID筛选
        condition($params['invite'] ?? '') && $where[] = ['m.invite', '=', $params['invite']];
        // 日期筛选
        empty($params['writeDate']) || $where[] = ['mr.create_time_stamp', 'between', betweenDate($params['writeDate'])];
        // 金币来源筛选
        condition($params['method'] ?? '') && $where[] = ['mr.method', 'in', explode(',', $params['method'])];
        // 货币类型筛选
        condition($params['currency'] ?? '') && $where[] = ['mr.currency', 'in', explode(',', $params['currency'])];
        // 默认查询当天
        empty($params['writeDate']) && empty($params['memberId']) && $where[] = ['mr.create_time_stamp', 'between', betweenDate($today . '~' . $today)];
        // 筛选字段
        $fields = ['mr.id rid', 'mr.member_id', 'mr.amount', 'mr.state', 'mr.method', 'mr.update_time', 'mr.currency',
            'm.avatar', 'm.invite', 'm.account', 'm.bind_type', 'm.email', 'm.id', 'm.state memberState'];
        // 筛选结果
        return MoneyRecordModel::alias('mr')->where($where)->field($fields)
            ->join(['sys_member' => 'm'], 'mr.member_id = m.id', 'left');
    }
}